//
//  PayViewController.m
//  ShrimpCrowdordering
//
//  Created by 郑洲 on 2018/8/28.
//  Copyright © 2018年 郑洲. All rights reserved.
//

#import "PayViewController.h"

#import "UIImage+GradientColor.h"
#import <AlipaySDK/AlipaySDK.h>
#import "WXApi.h"

@interface PayViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) BaseTableView *tableView;
@property (nonatomic, assign) BOOL isBalance;
@property (nonatomic, strong) NSMutableArray *payType;

@end

@implementation PayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setTitle:@"支付"];
    
    _isBalance = YES;
    _payType = [NSMutableArray arrayWithArray:@[@"0",@"1",@"0",@"0"]];
    
    self.tableView = [[BaseTableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NAVIGATION_BAR_HEIGHT - ScreenX375(49))];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = RGB_COLOR(244, 244, 244);
    [self.view addSubview:self.tableView];
    
    UIImage *bgImg = [UIImage gradientColorImageFromColors:@[REXADECIMALCOLOR(@"#ff1162"),REXADECIMALCOLOR(@"#fe4e4e")] gradientType:GradientTypeLeftToRight imgSize:CGSizeMake(SCREEN_WIDTH, ScreenX375(49))];
    UIButton *sureBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - NAVIGATION_BAR_HEIGHT - ScreenX375(49), SCREEN_WIDTH, ScreenX375(49))];
    [sureBtn setTitle:@"确定支付" forState:UIControlStateNormal];
    [sureBtn setTitleColor:REXADECIMALCOLOR(@"#ffffff") forState:UIControlStateNormal];
    sureBtn.titleLabel.font = Kfont(16);
    [sureBtn setBackgroundImage:bgImg forState:UIControlStateNormal];
    sureBtn.backgroundColor = REXADECIMALCOLOR(@"#ffd100");
    [sureBtn addTarget:self action:@selector(sureAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:sureBtn];
}

- (void)sureAction {
    if (_ordNum) {
        NSString *payType = @"";
        if ([self.payType[1] isEqualToString:@"1"]) {
            payType = @"0";
        }else if ([self.payType[2] isEqualToString:@"1"]) {
            payType = @"1";
        }
        [HttpManager postHttpRequestByPost:[NSString stringWithFormat:@"%@api/pay",REQUESTHEADER] andParameter:@{@"ordNum":_ordNum,@"isBalance":[NSString stringWithFormat:@"%d",_isBalance],@"payType":payType} success:^(id successResponse) {
            NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"code"]];
            if ([status isEqualToString:@"200"]) {
                NSString *appScheme = @"xiapin";
                
                if (successResponse[@"data"][@"data"]) {
                    // NOTE: 将签名成功字符串格式化为订单字符串,请严格按照该格式
                    if ([self.payType[1] isEqualToString:@"1"]) {
                        NSString *orderString = successResponse[@"data"][@"data"];
                        
                        // NOTE: 调用支付结果开始支付
                        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
                            NSLog(@"reslut = %@",resultDic);
                        }];
                    }else if ([self.payType[2] isEqualToString:@"1"]) {
                        NSDictionary *wechatPayDic = successResponse[@"data"][@"data"];
                        PayReq *req = [[PayReq alloc] init];
                        req.openID = [wechatPayDic objectForKey:@"appid"];
                        req.partnerId = [wechatPayDic objectForKey:@"partnerid"];
                        req.prepayId = [wechatPayDic objectForKey:@"prepayid"];
                        req.package = [wechatPayDic objectForKey:@"package"];
                        req.nonceStr = [wechatPayDic objectForKey:@"noncestr"];
                        req.timeStamp = [[wechatPayDic objectForKey:@"timestamp"] intValue];
                        req.sign = [wechatPayDic objectForKey:@"sign"];
                        [WXApi sendReq:req];
                    }
                }else {
                    [HttpManager showNoteMsg:@"支付成功"];
                }
            }
        } andFailure:^(id failureResponse) {
            [HttpManager showFail];
        }];
    }else {
        NSDictionary *parameter = @{@"userId":kNSUDefaultReadKey(@"userId"),@"proId":_proId,@"isCopyright":_isCopyRight,@"num":@"1"};
        if (_recName) {
            parameter = @{@"userId":kNSUDefaultReadKey(@"userId"),@"proId":_proId,@"isCopyright":_isCopyRight,@"num":@"1",@"recAddress":_recAddress,@"recArea":_recArea,@"recCity":_recCity,@"recName":_recName,@"recPhone":_recPhone,@"recProvince":_recProvince};
        }
        [HttpManager postHttpRequestByPost:[NSString stringWithFormat:@"%@api/createOrder",REQUESTHEADER] andParameter:parameter success:^(id successResponse) {
            NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"code"]];
            if ([status isEqualToString:@"200"]) {
                NSString *payType = @"";
                if ([self.payType[1] isEqualToString:@"1"]) {
                    payType = @"0";
                }else if ([self.payType[2] isEqualToString:@"1"]) {
                    payType = @"1";
                }
                [HttpManager postHttpRequestByPost:[NSString stringWithFormat:@"%@api/pay",REQUESTHEADER] andParameter:@{@"ordNum":[NSString stringWithFormat:@"%@",successResponse[@"data"][@"ordNum"]],@"isBalance":[NSString stringWithFormat:@"%d",self.isBalance],@"payType":payType} success:^(id successResponse) {
                    NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"code"]];
                    if ([status isEqualToString:@"200"]) {
                        NSString *appScheme = @"xiapin";
                        
                        if (successResponse[@"data"][@"data"]) {
                            // NOTE: 将签名成功字符串格式化为订单字符串,请严格按照该格式
                            if ([self.payType[1] isEqualToString:@"1"]) {
                                NSString *orderString = successResponse[@"data"][@"data"];
                                
                                // NOTE: 调用支付结果开始支付
                                [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
                                    NSLog(@"reslut = %@",resultDic);
                                }];
                            }else if ([self.payType[2] isEqualToString:@"1"]) {
                                NSDictionary *wechatPayDic = successResponse[@"data"][@"data"];
                                PayReq *req = [[PayReq alloc] init];
                                req.openID = [wechatPayDic objectForKey:@"appid"];
                                req.partnerId = [wechatPayDic objectForKey:@"partnerid"];
                                req.prepayId = [wechatPayDic objectForKey:@"prepayid"];
                                req.package = [wechatPayDic objectForKey:@"package"];
                                req.nonceStr = [wechatPayDic objectForKey:@"noncestr"];
                                req.timeStamp = [[wechatPayDic objectForKey:@"timestamp"] intValue];
                                req.sign = [wechatPayDic objectForKey:@"sign"];
                                [WXApi sendReq:req];
                            }
                        }else {
                            [HttpManager showNoteMsg:@"支付成功"];
                        }
                    }
                } andFailure:^(id failureResponse) {
                    [HttpManager showFail];
                }];
            }
        } andFailure:^(id failureResponse) {
            [HttpManager showFail];
        }];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 2;
    }
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            static NSString *cellId = @"imageCell";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
                UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH - ScreenX375(66)) / 2, ScreenX375(20), ScreenX375(66), ScreenX375(66))];
                [imageView sd_setImageWithURL:[NSURL URLWithString:_picUrl] placeholderImage:nil options:SDWebImageRetryFailed];
                [cell addSubview:imageView];
            }
            return cell;
        }else {
            static NSString *cellId = @"detailCell";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
                UIView *line = [[UIView alloc] initWithFrame:CGRectMake(ScreenX375(16), 0, SCREEN_WIDTH - ScreenX375(32), 0.5)];
                line.backgroundColor = REXADECIMALCOLOR(@"#eeeeee");
                [cell addSubview:line];
                
                UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(16), ScreenX375(15), ScreenX375(150), ScreenX375(18))];
                nameLabel.text = _proName;
                nameLabel.textColor = REXADECIMALCOLOR(@"#333333");
                nameLabel.font = Kfont(14);
                [cell addSubview:nameLabel];
                
                UILabel *moneyLabel = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - ScreenX375(116), ScreenX375(15), ScreenX375(100), ScreenX375(18))];
                moneyLabel.textColor = REXADECIMALCOLOR(@"#e24b44");
                moneyLabel.font = Kfont(14);
                moneyLabel.text = [NSString stringWithFormat:@"¥%@",_price];
                moneyLabel.textAlignment = NSTextAlignmentRight;
                [cell addSubview:moneyLabel];
            }
            return cell;
        }
    }else {
        NSArray *noteArr = @[@"余额支付",@"支付宝支付",@"微信支付",@"银行卡支付"];
        NSArray *imageArr = @[@"余额支付",@"支付宝",@"微信 支付",@"银行卡支付"];
        static NSString *cellId = @"payTypeCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            UIImageView *icon = [[UIImageView alloc] initWithFrame:CGRectMake(ScreenX375(16), ScreenX375(16), ScreenX375(18), ScreenX375(18))];
            icon.image = ImageWithName(imageArr[indexPath.row]);
            [cell addSubview:icon];
            
            UILabel *noteLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(56), 0, ScreenX375(150), ScreenX375(50))];
            noteLabel.text = noteArr[indexPath.row];
            noteLabel.textColor = REXADECIMALCOLOR(@"#333333");
            noteLabel.font = Kfont(14);
            [cell addSubview:noteLabel];
            
            UIButton *selectBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - ScreenX375(32), ScreenX375(17), ScreenX375(16), ScreenX375(16))];
            [selectBtn setImage:ImageWithName(@"未选择2") forState:UIControlStateNormal];
            [selectBtn setImage:ImageWithName(@"选择") forState:UIControlStateSelected];
            selectBtn.tag = 100 + indexPath.row;
            if (indexPath.row == 0 || indexPath.row == 1) {
                selectBtn.selected = YES;
            }
            [cell addSubview:selectBtn];
            
            UIView *line = [[UIView alloc] initWithFrame:CGRectMake(ScreenX375(16), ScreenX375(45.5), ScreenX375(343), ScreenX375(0.5))];
            line.backgroundColor = REXADECIMALCOLOR(@"#eeeeee");
            [cell addSubview:line];
        }
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UIButton *selectBtn = [self.view viewWithTag:100 + indexPath.row];
    if (indexPath.row == 0) {
        _isBalance = !_isBalance;
        selectBtn.selected = _isBalance;
    }else {
        for (int i = 1; i < 4; i++) {
            UIButton *selectBtn = [self.view viewWithTag:100 + i];
            selectBtn.selected = NO;
            [_payType replaceObjectAtIndex:i withObject:@"0"];
        }
        [_payType replaceObjectAtIndex:indexPath.row withObject:@"1"];
        selectBtn.selected = YES;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            return ScreenX375(120);
        }
        return ScreenX375(48);
    }
    return ScreenX375(46);
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 1) {
        return ScreenX375(36);
    }
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 1) {
        return ScreenX375(38);
    }
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 1) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ScreenX375(36))];
        view.backgroundColor = RGB_COLOR(244, 244, 244);
        
        UILabel *noteLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(16), 0, ScreenX375(150), ScreenX375(36))];
        noteLabel.text = @"选择支付方式";
        noteLabel.textColor = REXADECIMALCOLOR(@"#999999");
        noteLabel.font = Kfont(14);
        [view addSubview:noteLabel];
        
        return view;
    }
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (section == 1) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ScreenX375(36))];
        view.backgroundColor = RGB_COLOR(244, 244, 244);
        
        UILabel *noteLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(16), ScreenX375(10), ScreenX375(250), ScreenX375(18))];
        noteLabel.text = @"余额可以同时与其他方式支付，优先扣除余额";
        noteLabel.textColor = REXADECIMALCOLOR(@"#4a90e2");
        noteLabel.font = Kfont(12);
        [view addSubview:noteLabel];
        
        return view;
    }
    return nil;
}

@end
